//
//  ItemDetailViewController.m
//  Kjs-iOS
//
//  Created by cfq on 16/6/1.
//  Copyright © 2016年 jmhz. All rights reserved.
//

#import "ItemDetailViewController.h"
#import "TransverseSelectView.h"
#import "UIColor+KjsColor.h"
#import "ItemIntroductionCell.h"
#import "FinanciersInformationCell.h"
#import "InvestProtectionCell.h"
#import "InvestRecordCell.h"
#import "InvestRecordHeaderView.h"
#import "InvestRecordCell.h"
#import "InvestPayViewController.h"
#import "KJSRequest.h"
#import "ItemDetailModel.h"
#import "CommonUtil.h"
#import "AppDelegate.h"
#import "PRealAuth.h"
#import "ORealAuth.h"
#import "InvestSuccessViewController.h"
#import <QuickLook/QuickLook.h>
#import <YWFeedbackFMWK/YWFeedbackKit.h>
#import "LoginViewController.h"
#import "InvestSuccessViewController.h"
#define HotTel @"1399990000"
#define ScreenW [[UIScreen mainScreen] bounds].size.width //屏幕宽度
#define ScreenH [[UIScreen mainScreen] bounds].size.height //屏幕高度

typedef NS_ENUM(NSInteger,TableViewDisplayType) {
    IntroduceType = 1,
    FinanciersType,
    InvestProtectionType,
    InvestRecordType
};

@interface ItemDetailViewController()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate,QLPreviewControllerDataSource>
@property (weak, nonatomic) IBOutlet TransverseSelectView *transverseView;
@property (weak, nonatomic) IBOutlet UIButton *immediateInvestButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) TableViewDisplayType tableViewDisplayType;
@property (assign, nonatomic) CGFloat introWebViewHeight;
@property (assign, nonatomic) CGFloat introWebViewWidth;
@property (assign, nonatomic) CGFloat financeInfoHeight;
@property (strong,nonatomic) UIWebView *webView;


@property (assign,nonatomic) int rows;
@property (assign,nonatomic) int page;
@property (strong,nonatomic) ItemDetailModel *itemDetail;
@property (strong,nonatomic) NSString *introductionHTMLData;
@property (strong,nonatomic) NSString *proctionInfoHTMLData;


@property (nonatomic,weak) IBOutlet UILabel *itemNameLab;
@property (nonatomic,weak) IBOutlet UILabel *gdAnnualizedBenefitRateLab;
@property (nonatomic,weak) IBOutlet UILabel *interestDaysLab;
@property (nonatomic,weak) IBOutlet UILabel *targetMoneyLab;
@property (nonatomic,weak) IBOutlet UILabel *raiseRateLab;
@property (nonatomic,weak) IBOutlet UIProgressView *raiseRatePV;
@property (nonatomic,weak) IBOutlet UILabel *remindMoneyLab;
@property (nonatomic,weak) IBOutlet UILabel *lowLimitMoneyLab;
@property (weak,nonatomic) IBOutlet UILabel *itemStartTimeLable;
@property (weak,nonatomic) IBOutlet UILabel *itemEndTiemLab;
@property (weak,nonatomic) IBOutlet UILabel *gdBenefitModeLab;

@property (nonatomic,strong) NSString *url;
@property (nonatomic,strong) NSString *requestUrl;

@property (nonatomic,strong) UINavigationController *qlNavigationController;
@property (nonatomic,strong) QLPreviewController *qLPreviewController;

@property (nonatomic,strong) IBOutlet UIView *bottomBtnBGView;

@property (nonatomic,weak) IBOutlet UIImageView *kefuImageV;
@property (nonatomic,weak) IBOutlet UIImageView *telImageV;

@property (nonatomic, strong) YWFeedbackKit *feedbackKit;
@property (nonatomic, strong) NSString *appKey;

@property (nonatomic,strong) PRealAuth *pRealAuthInfo;
@property (nonatomic,strong) ORealAuth *oRealAuthInfo;
@property (nonatomic,assign) BOOL ifAuthPass;
@end

@implementation ItemDetailViewController
-(void)viewDidLoad{

    self.navigationItem.title = @"项目详情";
    self.naviTopView = NO;
    
    self.tableViewDisplayType = 1;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.webView  = [[UIWebView alloc] init];
    self.webView.delegate = self;
    
    self.interestDaysLab.adjustsFontSizeToFitWidth = YES;
    self.gdAnnualizedBenefitRateLab.adjustsFontSizeToFitWidth = YES;
    self.remindMoneyLab.adjustsFontSizeToFitWidth = YES;
    self.targetMoneyLab.adjustsFontSizeToFitWidth = YES;
    self.lowLimitMoneyLab.adjustsFontSizeToFitWidth = YES;
    
    self.url = [[NSString alloc] init];
    self.qLPreviewController = [[QLPreviewController alloc]initWithNibName:nil bundle:nil];
    self.qLPreviewController.navigationController.navigationBarHidden = YES;
    self.qLPreviewController.dataSource = self;
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(closeQuickLookAction:)];
    self.qLPreviewController.navigationItem.leftBarButtonItem = backButton;


    //添加lable边框
    self.itemStartTimeLable.layer.borderColor = [UIColor kjsMainColor].CGColor;
    self.itemStartTimeLable.layer.borderWidth = 1.0;
    //设置transverseView
    self.transverseView.titleArray = @[@"项目介绍",@"融资方信息",@"投资保障",@"投资记录"];
    self.transverseView.selectAction = ^(NSInteger selectLocation){
        self.tableViewDisplayType = selectLocation + 1;
        [self.tableView reloadData];
    };
    
//    self.immediateInvestButton.layer.borderColor = [UIColor whiteColor].CGColor;
//    self.immediateInvestButton.layer.borderWidth = 1.0;
//    self.immediateInvestButton.layer.cornerRadius = 10.0;
//    [self configeration];
//    [self getItemDetailWithItemId:self.itemId];
    
    //设置展示客服界面事件
    UITapGestureRecognizer *showKefu = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showKefuView)];
    self.kefuImageV.userInteractionEnabled = YES;
    [self.kefuImageV addGestureRecognizer:showKefu];
    
    //设置拨打电话事件
    UITapGestureRecognizer *showTel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sendTel)];
    self.telImageV.userInteractionEnabled = YES;
    [self.telImageV addGestureRecognizer:showTel];
}
-(void)viewWillAppear:(BOOL)animated{

    NSLog(@"itemId=%@-------------",self.itemId);
    [super viewWillAppear:animated];
    [self configeration];
    [self getItemDetailWithItemId:self.itemId];
    [self vaildRealAuth];
    [self.transverseView setSelectedLocation:0];
    self.tableViewDisplayType = IntroduceType;
}


#pragma mark - configurator
-(void)configTableView{
    [self.tableView registerNib:[UINib nibWithNibName:@"ItemIntroductionCell" bundle:nil] forCellReuseIdentifier:@"ItemIntroductionCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"FinanciersInformationCell" bundle:nil] forCellReuseIdentifier:@"FinanciersInformationCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"InvestProtectionCell" bundle:nil] forCellReuseIdentifier:@"InvestProtectionCell"];
     [self.tableView registerNib:[UINib nibWithNibName:@"InvestRecordCell" bundle:nil] forCellReuseIdentifier:@"InvestRecordCell"];
}
-(void)configeration
{
//    self.rows = 3;
//    self.page = 1;
    
    [self configTableView];
}
#pragma mark - custom method
- (void) goLogin
{
    NSLog(@"去登录");
    LoginViewController *loginVC = [[UIStoryboard storyboardWithName:@"Seconed" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginViewController"];
    loginVC.resultAction = ^(UserInfo *userInfo){
        NSLog(@"回到了fffffffffff");
        [self.transverseView setSelectedLocation:1];
        self.tableViewDisplayType = IntroduceType;
        [self.tableView reloadData];
       
    };
    [self displayViewController:loginVC];
}
- (void) getItemDetailWithItemId:(NSString *)itemId
{
    self.rows = 3;
    [KJSRequest GetItemDetailWithItemId:itemId page:0 rows:0 ret:^(ItemDetailModel *model) {
        self.itemDetail = model;
        for (int i = 0; i < [self.itemDetail.itemOtherInfo count]; i++) {
            switch (self.itemDetail.itemOtherInfo[i].itemInfoType) {
                case ItemIntroduction:
                    self.introductionHTMLData = [NSString stringWithFormat:@"%@",self.itemDetail.itemOtherInfo[i].itemOtherContext];
                    break;
                case ItemProctionInfo:
                    self.proctionInfoHTMLData = [NSString stringWithFormat:@"%@",self.itemDetail.itemOtherInfo[i].itemOtherContext];
                default:
                    break;
            }
        }
        NSLog(@"开始加载");
        [self.webView loadHTMLString:self.introductionHTMLData baseURL:nil];
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.numberStyle = NSNumberFormatterDecimalStyle;
        NSString *lowLimitMoneyStr = [formatter stringFromNumber:[NSNumber numberWithDouble:[self.itemDetail.itemPlan count]>0?self.itemDetail.itemPlan[0].lowLimitMoney:0]];
        NSString *targetMoneyStr = [formatter stringFromNumber:[NSNumber numberWithDouble:self.itemDetail.item.targetMoney]];
        NSString *remindMoneyStr = [formatter stringFromNumber:[NSNumber numberWithDouble:(self.itemDetail.item.targetMoney - self.itemDetail.item.raiseMoney)]];
        self.itemNameLab.text = self.itemDetail.item.itemName;
        //去掉小数点后多余的0
        NSString *gdAnnualizedBenefitRate = [NSString stringWithFormat:@"%.2lf％",self.itemDetail.item.gdAnnualizedBenefitRate*100];
        NSString * outNumber = [CommonUtil subZeorFrom:gdAnnualizedBenefitRate];
        self.gdAnnualizedBenefitRateLab.text = [NSString stringWithFormat:@"%@％",outNumber];
        self.lowLimitMoneyLab.text = [NSString stringWithFormat:@"起投金额：¥%@元",lowLimitMoneyStr];
        
        if ([[targetMoneyStr componentsSeparatedByString:@"."] count] == 1) {
            //若无小数，则补上.00
            targetMoneyStr = [NSString stringWithFormat:@"%@.00",targetMoneyStr];
        }
        self.targetMoneyLab.text = [NSString stringWithFormat:@"¥%@元",targetMoneyStr];
        
        if ([[remindMoneyStr componentsSeparatedByString:@"."] count] == 1) {
            //若无小数，则补上.00
            remindMoneyStr = [NSString stringWithFormat:@"%@.00",remindMoneyStr];
        }
        self.remindMoneyLab.text = [NSString stringWithFormat:@"¥%@元",remindMoneyStr];
        //时间戳转换显示
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"yyyy-MM-dd"];
        [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
        NSDate *itemStartTimeDate = [NSDate dateWithTimeIntervalSince1970:self.itemDetail.item.itemStartDate/1000];
        NSDate *itemEndTImeDate = [NSDate dateWithTimeIntervalSince1970:self.itemDetail.item.itemEndDate/1000];
        self.itemStartTimeLable.text = [df stringFromDate:itemStartTimeDate];
        self.itemEndTiemLab.text = [df stringFromDate:itemEndTImeDate];
        self.gdBenefitModeLab.text = [CommonUtil getGdBenefitModeStrWithMode:self.itemDetail.item.gdBenefitMode];
        self.raiseRatePV.progress = self.itemDetail.item.raiseMoney/self.itemDetail.item.targetMoney;
        self.raiseRateLab.text = [NSString stringWithFormat:@"%.0f％",self.itemDetail.item.raiseMoney/self.itemDetail.item.targetMoney*100];
        self.interestDaysLab.text = [NSString stringWithFormat:@"%d天",self.itemDetail.item.interestDays];
        
        
        switch (self.itemDetail.item.itemStatus) {
            case 7:
                [self.immediateInvestButton setTitle:@"立刻投资" forState:UIControlStateNormal];
                [self.bottomBtnBGView setBackgroundColor:[UIColor kjsMainColor]];
                [self.immediateInvestButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                break;
            case 8:
            {
                //创建日期格式化对象
                NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                //时间戳转换显示
                NSDateFormatter *df = [[NSDateFormatter alloc] init];
                [df setDateFormat:@"yyyy-MM-dd"];
                [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
                NSDate *itemStartTimeDate = [NSDate dateWithTimeIntervalSince1970:self.itemDetail.item.itemStartDate/1000];
                NSDate *nowDate = [NSDate date];
                //取两个日期对象的时间间隔：
                //这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:typedef double NSTimeInterval;
                NSTimeInterval time=[itemStartTimeDate timeIntervalSinceDate:nowDate];
                int days=((int)time)/(3600*24)+1;
                NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"距离项目开始还有    %d天",days]];
                [AttributedStr addAttribute:NSForegroundColorAttributeName
                                      value:[UIColor kjsMainColor]
                                      range:NSMakeRange(0, AttributedStr.length)];
                
                [AttributedStr addAttribute:NSFontAttributeName
                                      value:[UIFont systemFontOfSize:12.0]
                                      range:NSMakeRange(0, AttributedStr.length)];
                
                [AttributedStr addAttribute:NSFontAttributeName
                                      value:[UIFont systemFontOfSize:18.0]
                                      range:NSMakeRange(AttributedStr.length - 2, 2)];
                [self.immediateInvestButton setAttributedTitle:AttributedStr forState:UIControlStateNormal];
                [self.bottomBtnBGView setBackgroundColor:[UIColor colorWithRed:245/255.0f green:245/255.0f blue:245/255.0f alpha:1]];
            }
                break;
                break;
            case 9:
            {
                if ([self.benefitStepStr containsString:@"还款中"]) {
                    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:self.benefitStepStr];
                    [AttributedStr addAttribute:NSForegroundColorAttributeName
                                          value:[UIColor kjsMainColor]
                                          range:NSMakeRange(0, AttributedStr.length)];
                    [AttributedStr addAttribute:NSFontAttributeName
                                          value:[UIFont systemFontOfSize:18.0]
                                          range:NSMakeRange(0, AttributedStr.length)];
                    [self.immediateInvestButton setAttributedTitle:AttributedStr forState:UIControlStateNormal];
                    
                }else if ([self.benefitStepStr containsString:@"还款完成"]){
                    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:self.benefitStepStr];
                    [AttributedStr addAttribute:NSForegroundColorAttributeName
                                          value:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1]
                                          range:NSMakeRange(0, AttributedStr.length)];
                    [AttributedStr addAttribute:NSFontAttributeName
                                          value:[UIFont systemFontOfSize:18.0]
                                          range:NSMakeRange(0, AttributedStr.length)];
                    [self.immediateInvestButton setAttributedTitle:AttributedStr forState:UIControlStateNormal];
                }else{
                    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:@"已满标"];
                    [AttributedStr addAttribute:NSForegroundColorAttributeName
                                          value:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1]
                                          range:NSMakeRange(0, AttributedStr.length)];
                    [AttributedStr addAttribute:NSFontAttributeName
                                          value:[UIFont systemFontOfSize:18.0]
                                          range:NSMakeRange(0, AttributedStr.length)];
                    [self.immediateInvestButton setAttributedTitle:AttributedStr forState:UIControlStateNormal];
                }
                [self.bottomBtnBGView setBackgroundColor:[UIColor colorWithRed:245/255.0f green:245/255.0f blue:245/255.0f alpha:1]];
            }
                break;
            default:
                [self.immediateInvestButton setTitle:@"" forState:UIControlStateNormal];
                break;
        }
        [self.tableView reloadData];
    }];
    
}
-(void)showKefuView
{
//    [self _tryLogin];
    [GUATool showDialog:@"功能暂未开启" message:nil waitingTime:1.5];
}
- (void)_tryLogin
{
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];
    NSString *password = [[NSString alloc] init];
    password = [userDefaults objectForKey:@"password"];
    NSLog(@"userId=%@,password=%@",CurentDelegate.account.partyId,password);
    
    if ((![CurentDelegate.account.partyId isEqualToString:@""])&&(![password isEqualToString:@""])&&(CurentDelegate.account.partyId != NULL)) {
        self.feedbackKit = [[YWFeedbackKit alloc] initWithOpenIMUserId:CurentDelegate.account.partyId password:password appKey:CurentDelegate.appKey];
    }else{
        NSLog(@"不用用户名，密码");
        self.feedbackKit = [[YWFeedbackKit alloc] initWithAppKey:CurentDelegate.appKey];
    }

    _feedbackKit.customUIPlist = @{//是否开启录音功能，
                                   //如果不设置，会依据是否包含`YWFeedbackAudioExtentionFMWK.framework`来判断是否开启录音功能
                                   //如果设置为false,无论是否包含`YWFeedbackAudioExtentionFMWK.framework`，都会关闭录音功能
                                   //如果设置为true,且包含`YWFeedbackAudioExtentionFMWK.framework`的情况下，会开启录音功能
                                   @"enableAudio":@"true"
                                   };

    _feedbackKit.hideContactInfoView = YES;
    [self _openFeedbackViewController];
}

- (void)_openFeedbackViewController
{    
    [_feedbackKit makeFeedbackViewControllerWithCompletionBlock:^(YWFeedbackViewController *viewController, NSError *error) {
        
        if ( viewController != nil ) {
            //页面要补偿一个navgationbar的高度
            NSLog(@"展示view");
            CGRect viewFram = self.navigationController.view.frame;
            viewFram.size.height = viewFram.size.height + self.navigationController.navigationBar.frame.size.height;
            [self.navigationController.view setFrame:viewFram];
            
            [self.navigationController pushViewController:viewController animated:YES];
            viewController.navigationItem.title = @"客服";
            
            UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(actionQuitFeedback)];
            leftBarButton.tintColor = [UIColor whiteColor];
            viewController.navigationItem.leftBarButtonItem = leftBarButton;
            
            __weak typeof(self.navigationController) weakNav = self.navigationController;
            
            [viewController setOpenURLBlock:^(NSString *aURLString, UIViewController *aParentController) {
                UIViewController *webVC = [[UIViewController alloc] initWithNibName:nil bundle:nil];
                UIWebView *webView = [[UIWebView alloc] initWithFrame:webVC.view.bounds];
                webView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
                
                [webVC.view addSubview:webView];
                [weakNav pushViewController:webVC animated:YES];
                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:aURLString]]];
            }];
        }
    }];
}

- (void)actionQuitFeedback
{
    //取消高度补偿
    CGRect viewFram = self.navigationController.view.frame;
    viewFram.size.height = viewFram.size.height - self.navigationController.navigationBar.frame.size.height;
    [self.navigationController.view setFrame:viewFram];
    [self.navigationController popViewControllerAnimated:YES];

}
-(void)sendTel
{
    UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"是否拨打热线电话\n%@",HotTel]delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"拨打", nil];
    [alertV show];
}

-(void)vaildRealAuth
{
    if (CurentDelegate.account) {
        if ([CurentDelegate.account.type isEqualToString:@"p"]) {
            [self GetPRealInfo];
        }else if ([CurentDelegate.account.type isEqualToString:@"o"]){
            [self GetORealInfo];
        }
    }
}
-(void)GetPRealInfo
{
    [KJSRequest GetPRealAuthInfoWithPartyId:CurentDelegate.account.partyId ret:^(PRealAuthResultModel *model) {
        self.pRealAuthInfo = model.realAuthInfo;
        if ([self.pRealAuthInfo.auditingOpinion isEqualToString:@"0"]) {
            //审核不通过
            self.ifAuthPass = NO;
        }else{
            self.ifAuthPass = YES;
        }
    }];
}
-(void)GetORealInfo
{
    [KJSRequest GetORealAuthInfoWithPartyId:CurentDelegate.account.partyId ret:^(ORealAuthResultModel *model) {
        self.oRealAuthInfo = model.realAuthInfo;
        if ([self.oRealAuthInfo.auditingOpinion isEqualToString:@"0"]) {
            //审核不通过
            self.ifAuthPass = NO;
        }else{
            self.ifAuthPass = YES;
        }
    }];
}
#pragma mark - UIWebViewDelegate
- (void )webViewDidFinishLoad:(UIWebView  *)webView
{
    NSLog(@"webview加载完成");
    //重新设置cell高度
    self.introWebViewHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]floatValue];
    self.introWebViewWidth = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetWidth"]floatValue];
    NSLog(@"cell宽度=%lf",[[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetWidth"]floatValue]);

    [self.tableView reloadData];
}
#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (self.tableViewDisplayType == InvestRecordType) {
        if (CurentDelegate.account.partyId != NULL && ![CurentDelegate.account.partyId isEqualToString:@""])
        {
            return [self.itemDetail.investUsers count];
        }else{
            return 1;
        }
    }
    
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


    switch (self.tableViewDisplayType) {
        case IntroduceType:{
            ItemIntroductionCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ItemIntroductionCell"];
            [cell.introductionWebView setFrame:CGRectMake(0, 0, ScreenW, self.tableView.frame.size.height)];
            [cell setContext:self.introductionHTMLData];
            //去除cell点击效果
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            break;
        }
        case FinanciersType:{
            FinanciersInformationCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"FinanciersInformationCell"];
            self.financeInfoHeight = [cell setFinanceInfo:self.itemDetail.item];
            cell.userInteractionEnabled = true;
            //去除cell点击效果
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            break;
        }
        case InvestProtectionType:{
            if (CurentDelegate.account.partyId != NULL && ![CurentDelegate.account.partyId isEqualToString:@""])
            {
                InvestProtectionCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"InvestProtectionCell"];
                [cell initCellWithDocuments:self.itemDetail.itemDocuments ItemInfo:self.itemDetail.item];
                cell.showInfo = ^(NSString *url,NSString *fileName){
                    self.requestUrl = url;
                    NSLog(@"url=%@,filename=%@",url,fileName);
                    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:ConnectUrl(self.requestUrl)]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                        NSString *documentsDirectory=[paths objectAtIndex:0];
                        NSString *savedPath=[documentsDirectory stringByAppendingPathComponent:fileName];
                        [data writeToFile:savedPath atomically:YES];
                        self.url = savedPath;
                        NSLog(@"self.url=%@",self.url);
                        [self.qLPreviewController setCurrentPreviewItemIndex:0];
                        [self.qLPreviewController reloadData];
                        [self presentViewController:self.qlNavigationController animated:YES completion:nil];
                    }];
                    self.qlNavigationController = [[UINavigationController alloc]initWithRootViewController:self.qLPreviewController];
                };
                //去除cell点击效果
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }else{
                UITableViewCell *cell = [[UITableViewCell alloc] init];
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 320, 15)];
                label.adjustsFontSizeToFitWidth = YES;
                NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:@"需要登录才能查看内容"];
                [AttributedStr addAttribute:NSForegroundColorAttributeName
                                      value:[UIColor colorWithRed:51/255.0f green:51/255.0f blue:51/255.0f alpha:1]
                                      range:NSMakeRange(0, AttributedStr.length)];
                [AttributedStr addAttribute:NSForegroundColorAttributeName
                                      value:[UIColor kjsMainColor]
                                      range:NSMakeRange(2, 2)];
                [AttributedStr addAttribute:NSFontAttributeName
                                      value:[UIFont systemFontOfSize:15.0]
                                      range:NSMakeRange(0, AttributedStr.length)];
                label.attributedText = AttributedStr;
                [cell.contentView addSubview:label];
                //去除cell点击效果
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }
            break;
        case InvestRecordType:{
            if (CurentDelegate.account.partyId != NULL && ![CurentDelegate.account.partyId isEqualToString:@""]) {
                InvestRecordCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"InvestRecordCell"];
                cell.investUser = [self.itemDetail.investUsers count]>0?self.itemDetail.investUsers[indexPath.row]:nil;
                //去除cell点击效果
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }else{
                UITableViewCell *cell = [[UITableViewCell alloc] init];
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 320, 15)];
                
                label.adjustsFontSizeToFitWidth = YES;
                NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:@"需要登录才能查看内容"];
                [AttributedStr addAttribute:NSForegroundColorAttributeName
                                      value:[UIColor colorWithRed:51/255.0f green:51/255.0f blue:51/255.0f alpha:1]
                                      range:NSMakeRange(0, AttributedStr.length)];
                [AttributedStr addAttribute:NSForegroundColorAttributeName
                                      value:[UIColor kjsMainColor]
                                      range:NSMakeRange(2, 2)];
                [AttributedStr addAttribute:NSFontAttributeName
                                      value:[UIFont systemFontOfSize:15.0]
                                      range:NSMakeRange(0, AttributedStr.length)];
                label.attributedText = AttributedStr;

                [cell addSubview:label];
                //去除cell点击效果
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }
            break;
        default:{
            ItemIntroductionCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ItemIntroductionCell"];
            //去除cell点击效果
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (self.tableViewDisplayType == InvestRecordType) {
        if (CurentDelegate.account.partyId != NULL && ![CurentDelegate.account.partyId isEqualToString:@""]) {
            InvestRecordHeaderView * headerView = [[[NSBundle mainBundle] loadNibNamed:@"InvestRecordHeaderView" owner:self options:nil] firstObject];
            return headerView;
        }else{
            return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        }
    }

    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    switch (self.tableViewDisplayType) {
        case IntroduceType:{
            NSLog(@"cell高度＝%lf",self.introWebViewHeight);
            return self.introWebViewHeight;
            break;
        }
        case FinanciersType:{
            return self.financeInfoHeight;
            break;
        }
        case InvestProtectionType:{
            return 500;
            break;
        }
        case InvestRecordType:{
            return 44;
            break;
        }
        default:{
        
            return 200;
            break;
        }
            
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    NSLog(@"点击cell");

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (CurentDelegate.account.partyId == NULL || [CurentDelegate.account.partyId isEqualToString:@""]) {
        if (self.tableViewDisplayType == InvestProtectionType || self.tableViewDisplayType == InvestRecordType) {
            [self goLogin];
        }
    }
}
#pragma mark - QLPreviewControllerDataSource
- (NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller
{
    return 1;
}
- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    return [NSURL fileURLWithPath:self.url];
}
#pragma mark - 事件
- (IBAction)goImmediateInvest:(UIButton *)sender {
//    InvestSuccessViewController *investSuccessVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"InvestSuccessViewController"];
//    
//    [self displayViewController:investSuccessVC];
    NSLog(@"partyId=%@",self.itemDetail.item.partyId);
    if ([self.itemDetail.item.partyId isEqualToString:CurentDelegate.account.partyId]) {
        [GUATool showDialog:@"不能投资自己发起的项目" message:nil waitingTime:1.5];
    }else{
        switch (self.itemDetail.item.itemStatus) {
            case 7:
            {
                InvestPayViewController *investPayVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"InvestPayViewController"];
                investPayVC.item = self.itemDetail.item;
                investPayVC.itemPlan = self.itemDetail.itemPlan;
                investPayVC.investSuccess = ^(double investMoney){
                    InvestSuccessViewController *investSuccessVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"InvestSuccessViewController"];
                    investSuccessVC.investMoney = investMoney;
                    
                    [self displayViewController:investSuccessVC];
                };
                [self displayViewController:investPayVC];
            }
                break;
            case 8:
            {
                [GUATool showDialog:@"募集尚未开始" message:nil waitingTime:1.5];
            }
                break;
            default:
            {
                [GUATool showDialog:@"募集已结束" message:nil waitingTime:1.5];
            }
                break;
        }
        
    }
}
- (IBAction)closeQuickLookAction:(id)sender {
    NSLog(@"这里呗调用了");
    [_qlNavigationController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - overwrite method
- (void)displayViewController:(UIViewController *)viewController {
    NSLog(@"%@",CurentDelegate.account);
    if(CurentDelegate.account) {
        if (self.ifAuthPass == YES) {
            if ([CurentDelegate.account.type isEqualToString:@"p"]) {
                if ([CurentDelegate.account.levels integerValue] < 2) {
                    [GUATool showDialog:@"请先设置交易密码" message:nil waitingTime:1.5];
                }else if ([CurentDelegate.account.levels integerValue] < 3) {
                    [GUATool showDialog:@"请先绑定银行卡" message:nil waitingTime:1.5];
                }else{
                    [super displayViewController:viewController];
                }
            }else{
                if ([CurentDelegate.account.type isEqualToString:@"o"]) {
                    if ([CurentDelegate.account.levels integerValue] < 2) {
                        [GUATool showDialog:@"请先验证法人手机" message:nil waitingTime:1.5];
                    }else if ([CurentDelegate.account.levels integerValue] < 3) {
                        [GUATool showDialog:@"请先设置交易密码" message:nil waitingTime:1.5];
                    }else{
                        [super displayViewController:viewController];
                    }
                }
            }
    
        }else{
            [GUATool showDialog:@"请先进行实名认证" message:nil waitingTime:1.5];
        }
       
    }
    else {
        [CurentDelegate getAccountMessageAt:self ret:^(UserInfo *account) {
        }];
    }
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 1:
        {
            NSLog(@"拨打电话");
            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",HotTel];
            UIWebView *callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        }
            break;
            
        default:
            break;
    }
}
@end
